package com.qianqu.yuepai.application;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * ${自定义Application}
 *
 * @author weiqiliu
 * @version 1.0 2018/3/1
 */
public class CustomApplication extends com.qianqu.lib_base.application.CustomApplication {
    /**
     * 用于同进程间传递对象,临时存储,使用后要及时清理,避免内存溢出
     */
    private HashMap<String, Object> IntentHashMap = new HashMap<>();
    /**
     * 维护Activity 的list
     */
    private static List<Activity> mActivitys = Collections
            .synchronizedList(new LinkedList<Activity>());

    @Override
    public void onCreate() {
        super.onCreate();
        //多进程情况下避免多次调用,根据进程名来初始化
        int pid = android.os.Process.myPid();
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps != null && !runningApps.isEmpty()) {
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    if (procInfo.processName.equals("tim.com.androidframework")) {
                        init();
                        listenerMemory();
                        listenerActivityLify();
                    }
                }
            }
        }
        Log.e("app:","create_application");
    }

    /**
     * 简单描述:初始化资源,避免耗时操作
     */
    private void init() {
//        LogUtils.d("application init");
    }

    /**
     * 简单描述:监听系统内存
     */
    private void listenerMemory() {
        this.registerComponentCallbacks(new ComponentCallbacks2() {
            @Override
            public void onTrimMemory(int level) {
                //内存信息回调
                //         TRIM_MEMORY_BACKGROUND = 40;       应用处于前台运行,位于LRU表开头
                //         TRIM_MEMORY_COMPLETE = 80;         应用处于前台运行,位于LRU表末尾
                //         TRIM_MEMORY_MODERATE = 60;         应用处于前台运行,位于LRU表中部
                //         TRIM_MEMORY_RUNNING_CRITICAL = 15; 应用处于前台运行,内存更低了,存在被系统kill风险
                //         TRIM_MEMORY_RUNNING_LOW = 10;      应用处于前台运行,内存很低了,影响性能
                //         TRIM_MEMORY_RUNNING_MODERATE = 5;  应用处于前台运行,内存有点低
                //         TRIM_MEMORY_UI_HIDDEN = 20;        应用从前台切换到后台
            }

            @Override
            public void onConfigurationChanged(Configuration newConfig) {
                //配置信息改变回调
            }

            @Override
            public void onLowMemory() {
                //Android 4.0以前使用的方法
            }
        });
    }

    /**
     * 简单描述:监听activity生命周期
     */
    private void listenerActivityLify() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                    pushActivity(activity);
                }

                @Override
                public void onActivityStarted(Activity activity) {

                }

                @Override
                public void onActivityResumed(Activity activity) {

                }

                @Override
                public void onActivityPaused(Activity activity) {

                }

                @Override
                public void onActivityStopped(Activity activity) {

                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                    if (null == mActivitys || mActivitys.isEmpty()) {
                        return;
                    }
                    if (mActivitys.contains(activity)) {
                        /**
                         *  监听到 Activity销毁事件 将该Activity 从list中移除
                         */
                        popActivity(activity);
                    }
                }
            });
        }
    }

    public HashMap<String, Object> getIntentHashMap() {
        return IntentHashMap;
    }

    public void cleanIntentHashMap() {
        IntentHashMap.clear();
    }

    /**
     * @param activity 作用说明 ：添加一个activity到管理里
     */
    public void pushActivity(Activity activity) {
        mActivitys.add(activity);
//        LogUtils.d("activityList add" + activity.getLocalClassName());
    }

    /**
     * @param activity 作用说明 ：删除一个activity在管理里
     */
    public void popActivity(Activity activity) {
        mActivitys.remove(activity);
//        LogUtils.d("activityList pop" + activity.getLocalClassName());
    }


    /**
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    public static Activity currentActivity() {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return null;
        }
        Activity activity = mActivitys.get(mActivitys.size() - 1);
        return activity;
    }

    /**
     * 结束当前Activity（栈中最后一个压入的）
     */
    public static void finishCurrentActivity() {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return;
        }
        Activity activity = mActivitys.get(mActivitys.size() - 1);
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(Activity activity) {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return;
        }
        if (activity != null) {
            mActivitys.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class<?> cls) {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return;
        }
        for (Activity activity : mActivitys) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 按照指定类名找到activity
     *
     * @param cls
     * @return
     */
    public static Activity findActivity(Class<?> cls) {
        Activity targetActivity = null;
        if (mActivitys != null) {
            for (Activity activity : mActivitys) {
                if (activity.getClass().equals(cls)) {
                    targetActivity = activity;
                    break;
                }
            }
        }
        return targetActivity;
    }

    /**
     * @return 作用说明 ：获取当前最顶部activity的实例
     */
    public Activity getTopActivity() {
        Activity mBaseActivity = null;
        synchronized (mActivitys) {
            final int size = mActivitys.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = mActivitys.get(size);
        }
        return mBaseActivity;

    }

    /**
     * @return 作用说明 ：获取当前最顶部的acitivity 名字
     */
    public String getTopActivityName() {
        Activity mBaseActivity = null;
        synchronized (mActivitys) {
            final int size = mActivitys.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = mActivitys.get(size);
        }
        return mBaseActivity.getClass().getName();
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        if (mActivitys == null) {
            return;
        }
        for (Activity activity : mActivitys) {
            activity.finish();
        }
        mActivitys.clear();
    }

    /**
     * 退出应用程序
     */
    public static void appExit() {
        try {
//            LogUtils.e("app exit");
            finishAllActivity();
        } catch (Exception e) {
        }
    }

}
